<template>
  <div class="container">
      <div id="app">
    <div class="sidebar">
      <el-input
        id="search-input"
        placeholder="搜索任务目录名称"
        prefix-icon="el-icon-search"
      />
      <el-tree
        :data="treeData"
        :props="defaultProps"
        :expand-on-click-node="false"
        :default-expanded-keys="defaultExpandedKeys"
        node-key="id"
        ref="tree"
        class="tree-menu"
        @node-click="handleNodeClick"
      >
        <span class="custom-tree-node" slot-scope="{ node, data }">
          <span class="tree-node-content">
            <i :class="data.icon" v-if="data.icon"></i>
            <span class="node-label">{{ node.label }}</span>
          </span>
        </span>
      </el-tree>
    </div>
    <div class="main-content">
      <div class="top-action">
        <el-button id="button" type="primary" @click="showAddTaskDialog">新增</el-button>
        <div class="search-refresh">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索任务名称"
            prefix-icon="el-icon-search"
            @keyup.enter.native="handleSearch"
            class="search-input"
          />
          <i class="el-icon-refresh refresh-btn" @click="handleResetSearch"></i>
        </div>
      </div>
      <el-table
        id="task-table"
        :data="tableData"
        style="width: 100%"
        header-row-class-name="table-header"
      >
        <el-table-column
          id="task-name-column"
          prop="name"
          label="任务名称"
        />
        <el-table-column
          id="task-type-column"
          prop="type"
          label="采集类型"
          width="180"
        >
          <template slot-scope="scope">
            <el-button 
              type="primary" 
              plain 
              size="mini" 
              class="type-button"
            >
              {{ scope.row.type }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          id="task-cycle-column"
          prop="cycle"
          label="任务周期"
          width="180"
        />
        <el-table-column
          id="task-status-column"
          prop="status"
          label="状态"
          width="180"
        >
          <template slot-scope="scope">
            <el-tag 
              :class="scope.row.status === '停用' ? 'status-disabled' : 'status-enabled'"
            >
              {{ scope.row.status }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          id="task-update-column"
          prop="updateTime"
          label="最后更新时间"
          width="200"
        />
        <el-table-column
          id="task-operator-column"
          prop="operator"
          label="操作人"
        />
        <el-table-column
          id="task-action-column"
          label="操作"
          width="180"
        >
          <template slot-scope="scope">
            <el-link :underline="false" @click="handleEdit(scope.$index, scope.row)" class="action-link">编辑</el-link>
            <el-divider direction="vertical"/>
            <el-link :underline="false" @click="handleToggle(scope.$index, scope.row)" class="action-link">
              {{ scope.row.status === '启用' ? '停用' : '启用' }}
            </el-link>
            <el-divider direction="vertical"/>
            <el-link :underline="false" @click="handleDelete(scope.$index, scope.row)" class="action-link">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <div class="pagination-total">共 {{ pagination.total }} 条</div>
        <el-pagination
          id="pagination"
          background
          layout="sizes, prev, pager, next, jumper"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pagination.size"
          :current-page="pagination.current"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        >
        </el-pagination>
      </div>
    </div>
    
    <!-- 新增任务对话框 -->
    <el-dialog
      title="新增任务"
      :visible.sync="addTaskDialogVisible"
      width="500px"
      :before-close="handleCloseAddTaskDialog"
    >
      <el-form :model="addTaskForm" label-width="100px" ref="addTaskForm">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="addTaskForm.taskName" placeholder="请输入任务名称"></el-input>
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-select v-model="addTaskForm.taskType" placeholder="请选择任务类型" style="width: 100%;">
            <el-option label="类型1" :value="1"></el-option>
            <el-option label="类型2" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="任务周期" prop="taskCron">
          <el-input v-model="addTaskForm.taskCron" placeholder="请输入任务周期"></el-input>
        </el-form-item>
        <el-form-item label="任务状态" prop="status">
          <el-radio-group v-model="addTaskForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleCloseAddTaskDialog">取 消</el-button>
        <el-button type="primary" @click="handleAddTaskConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
  </div>

  
  </template><script lang="js">
import {
  getMenuTree,
  getTaskPage,
  deleteTask,
  updateTaskStatus,
  addTask
} from '@/api/TaskOverviewAPI.js'

export default {
  data() {
    return {
      // 树形菜单数据
      treeData: [],
      defaultProps: {
        children: 'children',
        label: 'menuName'
      },
      defaultExpandedKeys: [],
      isAllExpanded: false,
      // 表格数据
      tableData: [],
      // 分页数据
      pagination: {
        total: 0,
        size: 10,
        current: 1,
        pages: 0
      },
      // 搜索关键字
      searchKeyword: '',
      // 当前选中的菜单ID
      currentMenuId: null,
      // 新增任务表单
      addTaskForm: {
        taskName: '',
        taskType: '',
        taskCron: '',
        status: 1
      },
      // 新增任务对话框可见性
      addTaskDialogVisible: false
    }
  },
  created() {
    // 页面初始化时调用分类接口展示树形数据
    this.loadMenuTree();
    // 初始化时加载默认列表数据
    this.loadTaskList();
  },
  methods: {
    // 加载菜单树
    async loadMenuTree() {
      try {
        const data = await getMenuTree();
        this.treeData = data || [];
        // 默认展开第一个节点
        if (data && data.length > 0) {
          this.defaultExpandedKeys = [data[0].id];
          // 默认选中第一个节点
          this.currentMenuId = data[0].id;
        }
      } catch (error) {
        console.error('获取菜单树失败:', error);
        this.$message.error('获取菜单树失败');
      }
    },
    // 加载任务列表
    async loadTaskList() {
      try {
        const params = {
          countTotal: true,
          pageNo: this.pagination.current,
          pageSize: this.pagination.size,
          keyword: this.searchKeyword,
          menuId: this.currentMenuId
        };
        
        const data = await getTaskPage(params);
        
        // 更新表格数据
        this.tableData = (data.list || []).map(item => ({
          id: item.id,
          name: item.taskName,
          type: item.taskType,
          cycle: item.taskCron,
          status: item.status === 1 ? '启用' : '停用',
          updateTime: item.updateTime,
          operator: item.operator
        }));
        
        // 更新分页信息
        this.pagination.total = data.total || 0;
      } catch (error) {
        console.error('获取任务列表失败:', error);
        this.$message.error('获取任务列表失败');
      }
    },
    handleEdit(index, row) {
      console.log('Edit:', index, row);
      this.$message.info('此功能正在开发中');
    },
    handleToggle(index, row) {
      console.log('Toggle:', index, row);
      // 弹出启用/停用确认框
      const action = row.status === '启用' ? '停用' : '启用';
      this.$confirm(`确定要${action}该任务吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用启用/停用接口
          await updateTaskStatus({
            id: row.id,
            status: row.status === '启用' ? 0 : 1
          });
          
          this.$message.success(`${action}成功`);
          // 刷新列表
          this.loadTaskList();
        } catch (error) {
          console.error(`${action}失败:`, error);
          this.$message.error(`${action}失败`);
        }
      }).catch(() => {
        // 用户取消操作
        this.$message.info('已取消操作');
      });
    },
    handleDelete(index, row) {
      console.log('Delete:', index, row);
      // 弹出删除确认框
      this.$confirm('确定要删除该任务吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          // 调用删除接口
          await deleteTask(row.id);
          this.$message.success('删除成功');
          // 刷新列表
          this.loadTaskList();
        } catch (error) {
          console.error('删除失败:', error);
          this.$message.error('删除失败');
        }
      }).catch(() => {
        // 用户取消操作
        this.$message.info('已取消删除');
      });
    },
    handleNodeClick(data) {
      console.log('Node clicked:', data);
      // 设置当前节点为选中状态
      this.$refs.tree.setCurrentKey(data.id);
      // 更新当前选中的菜单ID
      this.currentMenuId = data.id;
      // 重置分页到第一页
      this.pagination.current = 1;
      // 重新加载任务列表
      this.loadTaskList();
    },
    toggleExpand() {
      // 展开/收起所有节点
      if (this.isAllExpanded) {
        this.$refs.tree.setExpandedKeys([]);
      } else {
        const allKeys = this.getAllNodeKeys(this.treeData);
        this.$refs.tree.setExpandedKeys(allKeys);
      }
      this.isAllExpanded = !this.isAllExpanded;
    },
    // 处理搜索
    handleSearch() {
      // 重置分页到第一页
      this.pagination.current = 1;
      // 重新加载任务列表
      this.loadTaskList();
    },
    // 重置搜索
    handleResetSearch() {
      // 清空搜索关键字
      this.searchKeyword = '';
      // 重置分页到第一页
      this.pagination.current = 1;
      // 重新加载任务列表
      this.loadTaskList();
    },
    // 每页条数变更事件
    handleSizeChange(newSize) {
      this.pagination.size = newSize;
      this.pagination.current = 1; // 重置到第一页
      this.loadTaskList();
    },
    // 当前页码变更事件
    handleCurrentChange(newPage) {
      this.pagination.current = newPage;
      this.loadTaskList();
    },
    getAllNodeKeys(data) {
      const keys = [];
      data.forEach(item => {
        keys.push(item.id);
        if (item.children && item.children.length > 0) {
          keys.push(...this.getAllNodeKeys(item.children));
        }
      });
      return keys;
    },
    // 显示新增任务对话框
    showAddTaskDialog() {
      // 重置表单数据
      this.addTaskForm = {
        taskName: '',
        taskType: '',
        taskCron: '',
        status: 1
      };
      // 显示对话框
      this.addTaskDialogVisible = true;
    },
    // 关闭新增任务对话框
    handleCloseAddTaskDialog() {
      this.addTaskDialogVisible = false;
    },
    // 新增任务确认
    async handleAddTaskConfirm() {
      // 非空校验
      if (!this.addTaskForm.taskName) {
        this.$message.warning('请输入任务名称');
        return;
      }
      if (!this.addTaskForm.taskType) {
        this.$message.warning('请选择任务类型');
        return;
      }
      if (!this.addTaskForm.taskCron) {
        this.$message.warning('请输入任务周期');
        return;
      }
      
      try {
        // 调用新增任务接口
        await addTask(this.addTaskForm);
        this.$message.success('新增任务成功');
        // 关闭对话框
        this.handleCloseAddTaskDialog();
        // 刷新列表
        this.loadTaskList();
      } catch (error) {
        console.error('新增任务失败:', error);
        this.$message.error('新增任务失败');
      }
    }
  }
}</script>

<style lang="scss" scoped>

  .container{
    background-color: #F5F7FA;
    padding: 16px 32px;
    font-family: "Microsoft YaHei", sans-serif;
    height: 100%;
    overflow: auto
    
  }
  
#app {
  display: flex;
  height: 100%;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", Arial, sans-serif;
}

.sidebar {
  width: 18%;
  min-width: 100px;
  padding: 20px;
  background-color: #FFFFFF;
  border-right: 1px solid #E5E7EB;

  #search-input {
    width: 100%;
    height: 36px;
    border: 1px solid #E5E7EB;
    background: #FFFFFF;
    border-radius: 4px;
    margin-bottom: 16px;

    input::placeholder {
      color: #9CA3AF;
    }
  }

  .tree-menu {
    background-color: #FFFFFF;
    border: none;
    margin-top: 20px;

    .el-tree-node {
      &:focus > .el-tree-node__content {
        background-color: #EFF6FF;
        color: #1D4ED8;
      }

      &.is-current > .el-tree-node__content {
        background-color: #EFF6FF;
        color: #1D4ED8;
      }
    }

    .el-tree-node__content {
      height: 40px;
      line-height: 40px;
      color: #374151;
      background-color: #FFFFFF;
      border-radius: 4px;
      margin-bottom: 4px;

      &:hover {
        background-color: #F3F4F6;
      }

      .custom-tree-node {
        display: flex;
        align-items: center;
        width: 100%;

        .tree-node-content {
          display: flex;
          align-items: center;

          i {
            margin-right: 8px;
            color: #374151;
            font-size: 14px;
          }

          .node-label {
            font-size: 14px;
          }
        }
      }
    }

    .el-tree-node__children {
      .el-tree-node__content {
        padding-left: 40px;
      }
    }
  }
}

.main-content {
  width: 80%;
  height: 100%;
  overflow: auto;
  margin-left: 20px;

  .top-action {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 12px;
    box-sizing: border-box;
    background-color: #fff;

    #button {
      width: 80px;
      height: 36px;
      background-color: #1D4ED8;
      border-radius: 4px;
      color: #FFFFFF;
    }

    .search-refresh {
      display: flex;
      align-items: center;

      .search-input {
        width: 200px;
        height: 36px;
        margin-right: 10px;

        .el-input__inner {
          border: 1px solid #E5E7EB;
          background: #FFFFFF;
          border-radius: 4px;
          color: #374151;

          &::placeholder {
            color: #9CA3AF;
          }
        }
      }

      .refresh-btn {
        font-size: 16px;
        color: #9CA3AF;
        cursor: pointer;
        width: 36px;
        height: 36px;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #E5E7EB;
        border-radius: 50%;
        background-color: #FFFFFF;

        &:hover {
          color: #1D4ED8;
          border-color: #1D4ED8;
        }
      }
    }
  }

  #task-table {
    margin-bottom: 20px;
    border-radius: 4px;
    padding: 12px;
    box-sizing: border-box;
    overflow: hidden;

    .table-header {
      background-color: #F3F4F6;
      color: #6B7280;
      font-weight: bold;
    }

    .type-button {
      border: 1px solid #1D4ED8;
      color: #1D4ED8;
      border-radius: 4px;
      height: 24px;
      line-height: 22px;
      padding: 0 10px;
    }

    .status-disabled {
      background-color: #FEE2E2;
      color: #DC2626;
      border-radius: 4px;
      height: 24px;
      line-height: 22px;
      padding: 0 10px;
    }

    .status-enabled {
      background-color: #DCFCE7;
      color: #10B981;
      border-radius: 4px;
      height: 24px;
      line-height: 22px;
      padding: 0 10px;
    }

    .action-link {
      color: #1D4ED8;
    }
  }

  .pagination-container {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding: 20px;
    background-color: #FFFFFF;
    border-top: 1px solid #E5E7EB;

    .pagination-total {
      color: #6B7280;
      font-size: 14px;
    }

    #pagination {
      .el-pagination__sizes {
        .el-input {
          margin-right: 10px;
          
          .el-input__inner {
            border: 1px solid #E5E7EB;
            background: #FFFFFF;
            color: #374151;
            border-radius: 4px;
            height: 32px;
            line-height: 32px;
          }
        }
      }

      .el-pager li {
        background-color: #FFFFFF;
        color: #6B7280;
        border: 1px solid #E5E7EB;
        border-radius: 4px;
        min-width: 32px;
        height: 32px;
        line-height: 30px;
        text-align: center;
        margin: 0 4px;
        font-size: 14px;

        &:hover {
          color: #1D4ED8;
        }

        &.active {
          background-color: #1D4ED8;
          color: #FFFFFF;
          border-color: #1D4ED8;
        }
      }

      .btn-prev, .btn-next {
        background-color: #FFFFFF;
        color: #6B7280;
        border: 1px solid #E5E7EB;
        border-radius: 4px;
        min-width: 32px;
        height: 32px;
        line-height: 30px;
        text-align: center;
        margin: 0 4px;
        font-size: 14px;

        &:hover {
          color: #1D4ED8;
          border-color: #1D4ED8;
        }

        &.disabled {
          color: #D1D5DB;
          border-color: #E5E7EB;
          background-color: #F9FAFB;
        }
      }

      .el-pagination__jump {
        margin-left: 16px;
        color: #374151;
        font-size: 14px;

        .el-pagination__editor {
          margin: 0 8px;
          width: 50px;
          height: 32px;
          
          .el-input__inner {
            border: 1px solid #E5E7EB;
            background: #FFFFFF;
            color: #374151;
            border-radius: 4px;
            text-align: center;
            height: 32px;
            line-height: 32px;
          }
        }
      }
    }

    .pagination-jump {
      display: flex;
      align-items: center;
      color: #374151;
      font-size: 14px;

      .jump-input {
        width: 50px;
        height: 32px;
        margin: 0 8px;
        
        .el-input__inner {
          border: 1px solid #E5E7EB;
          background: #FFFFFF;
          color: #374151;
          border-radius: 4px;
          text-align: center;
          height: 32px;
          line-height: 32px;
        }
      }
    }
  }
}</style>